package com.yhty.dao.impl;

import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.stereotype.Repository;
import com.yhty.dao.RentDao;
import com.yhty.model.Rent;
import com.yhty.utils.DateUtil;

/**
 * 租赁关系dao实现类
 * 
 * @author roy 2011-2-28 下午03:07:30
 */
@Repository("rentDao")
public class RentDaoImpl implements RentDao {
	private JdbcTemplate jdbcTemplate;

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	@Resource(name = "jdbcTemplate")
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	private Long getId(){
		String sql = "SELECT RENT_SEQ_ID.NEXTVAL FROM DUAL";
		return jdbcTemplate.queryForLong(sql);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yhty.dao.RentDao#add(com.yhty.model.Rent)
	 */
	public Long add(Rent r) {
		Long rent_id = getId();
		String sql = "insert into rent(id,file_code,rental,managmentExpenses,"
				+ "r_date,e_date,deposit,customer,status)"
				+ "values(?,?,?,?,?,?,?,?,?)";
		getJdbcTemplate().update(
				sql,
				new Object[] {rent_id, r.getFile_code(), r.getRental(),
						r.getManagmentExpenses(), r.getR_date(), r.getE_date(),
						r.getDeposit(), r.getCustomer(), r.getStatus() });
		return rent_id;
	}

	/*
	 * 逻辑移除租赁关系
	 * @see com.yhty.dao.RentDao#remove(com.yhty.model.Rent)
	 */
	public void remove(Long id) {
		String sql = "update rent set status=2 where id=?";
		getJdbcTemplate().update(sql, id);
	}

	/*
	 * 匿名内部类进行数据解析，效率第一
	 * 
	 * @see com.yhty.dao.RentDao#getAll()
	 */
	public List<Rent> getAll() {
		String sql = "select * from rent where status=1";
		return getJdbcTemplate().query(sql, new RowMapper<Rent>() {
			public Rent mapRow(java.sql.ResultSet rs, int rowNum)
					throws SQLException {
				Rent r = new Rent();
				r.setId(rs.getLong("id"));
				r.setCustomer(rs.getString("customer"));
				r.setDeposit(rs.getFloat("deposit"));
				r.setE_date(DateUtil.getDate(rs.getTimestamp("e_date")));
				r.setFile_code(rs.getString("file_code"));
				r.setManagmentExpenses(rs.getFloat("managmentExpenses"));
				r.setR_date(DateUtil.getDate(rs.getTimestamp("r_date")));
				r.setRental(rs.getFloat("rental"));
				r.setStatus(rs.getInt("status"));
				return r;
			}
		});
	}

	/*
	 * 根据ID获取出租关系
	 * @see com.yhty.dao.RentDao#getById(java.lang.Long)
	 */
	public Rent getById(Long id) {
		String sql = "select * from rent where id="+id;
		return getJdbcTemplate().queryForObject(sql,
				ParameterizedBeanPropertyRowMapper.newInstance(Rent.class));
	}

}
